﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Linq.Expressions;

namespace CatsAndMice.Models
{
    public abstract class AbstractModel : INotifyPropertyChanged
    {
        protected int _id;
        public int ID
        {
            get
            {
                return _id;
            }
        }
        protected AbstractModel(int id)
        {
            _id = id;
        }


        public event PropertyChangedEventHandler PropertyChanged;
        protected bool SetProperty<T>(ref T field, T value, Expression<Func<T>> propertyExpression)
        {
            return SetProperty(ref field, value, propertyExpression, true);
        }

        protected bool SetProperty<T>(ref T field, T value, Expression<Func<T>> propertyExpression, bool checkChanged)
        {
            var changed = !EqualityComparer<T>.Default.Equals(field, value);
            if (changed || !checkChanged)
            {
                field = value;
                RaisePropertyChanged(ExtractPropertyName(propertyExpression));
            }
            return changed;
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
        {
            var memberExpression = propertyExpression.Body as MemberExpression;
            if (memberExpression == null)
                throw new ArgumentException("Expression must be a MemberExpression.", "propertyExpression");
            return memberExpression.Member.Name;
        }
    }
}